﻿using System.Collections.Generic;
using UnityEngine;


public class StateMachine
{
    //存储一个状态机所拥有的状态
    Dictionary<string, State> _stateDic = new Dictionary<string, State>();
    //当前状态
    State _currentState;

    //上一个状态
    State _lastState;
    public StateMachine(){}
    //注册状态
    public void RegisterState(string key,State value)
    {
        _stateDic.Add(key, value);
    }
    //设置默认状态
    public void SetDefaultState(string key)
    {
        if (!_stateDic.ContainsKey(key))
        {
            Debug.LogError("没有此状态，设置默认状态失败");
            return;
        }
        //找到字典的key所对应的状态
        _currentState = _stateDic[key];   
    }
    //切换状态
    public void ChangeState(string key)
    {
        if (!_stateDic.ContainsKey(key))
        {
            Debug.LogError("没有此状态无法设置，切换状态失败");
            return;
        }
        //找到字典的key所对应的状态
        _currentState = _stateDic[key];
    }

    //机器工作的方法
    public void DoWork()
    {
        if (_currentState != _lastState)
        {
            _currentState.EnterState();
            _lastState = _currentState;
        }
        _currentState.UpdateState();
        if (_currentState != _lastState)
        {
            _lastState.ExitState();
        }
    }
}
